import 'package:fish_redux/fish_redux.dart';
import 'dart:io';
import '../../app_files.dart';
import 'action.dart';
import 'state.dart';
import '../OrderView/model/order_view_model.dart';
import 'dart:convert';

Effect<PatrolOrderViewState> buildEffect() {
  return combineEffects(<Object, Effect<PatrolOrderViewState>>{
    PatrolOrderViewAction.onTapAddPic: _onTapAddPic,
    PatrolOrderViewAction.onSubmit: _onSubmit,
    PatrolOrderViewAction.onTapPic: _onTapPic,
    Lifecycle.initState: _initState,
  });
}

void _onAction(Action action, Context<PatrolOrderViewState> ctx) {}

void _onTapPic(Action action, Context<PatrolOrderViewState> ctx) async {
  OrderConfigModel model = action.payload['model'];
  var file = action.payload['data'];
  int res =
  await CommonUtils.showActionSheet(ctx.context, button: ['查看', '删除']);
  if (res == 1) {
    model.imageList.remove(file);
    ctx.dispatch(PatrolOrderViewActionCreator.onAction());
  } else if (res == 0) {
    await CommonUtils.showMediaAlbumView(
      ctx.context,
      initialIndex: model.imageList.indexOf(file),
      files: model.imageList,
    );
  }
}

void _onTapAddPic(Action action, Context<PatrolOrderViewState> ctx) async {
  OrderConfigModel model = action.payload;
  AssetEntityFile imgFile = await CommonUtils.showOrderImagePicker(ctx.context,
      type: 1, info: ctx.state.pointInfo);
  if (imgFile != null) {
    model.imageList.add(imgFile);
    ctx.dispatch(PatrolOrderViewActionCreator.onAction());
  }
}

void _initState(Action action, Context<PatrolOrderViewState> ctx) async {

  ResultData res = await CommonNetWork.staffCheckConfig(
    worktplType: 2,
    worktplUsertype: '1',
  );
  if (res.success) {
    Map data = res.data['data'];

    String listJson = data['worktplItem'];
    List list = jsonDecode(listJson);
    List<OrderConfigModel> items = list
        .map<OrderConfigModel>((e) => OrderConfigModel.fromConfigJson(e))
        .toList();
    ctx.dispatch(PatrolOrderViewActionCreator.onGetData(items));
  } else {
    CommonUtils.showErrorInfo(ctx.context, res.desc);
  }
}

void _onSubmit(Action action, Context<PatrolOrderViewState> ctx) async {
  String errStr;
  for (OrderConfigModel model in ctx.state.items) {
    if (model.values.length == 0 && !model.hasOther && model.isNormal != true) {
      errStr = '请选择<${model.configName}>检测内容';
      break;
    }

    if (model.hasOther && model.textEditingController.text.length == 0) {
      errStr = '请填写<${model.configName}>问题描述';
      break;
    }
  }

  if (errStr != null) {
    CommonUtils.showAlertView(ctx.context, errStr);
  } else {
    CommonUtils.pushRoute(ctx.context, RoutePath.patrolOrderResultView, arguments: {
      'info': ctx.state.pointInfo,
      'items': ctx.state.items,
    });
  }
}
